/*
 *所有关于equipmentoperationlogs类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*equipmentoperationlogsService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VolPro.Core.BaseProvider;
using VolPro.Core.Extensions.AutofacManager;
using VolPro.Entity.DomainModels;
using System.Linq;
using VolPro.Core.Utilities;
using System.Linq.Expressions;
using VolPro.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using SMes.DbMethod.IRepositories;
using System.Threading.Tasks;
using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using SMes.DbMethod.ViewModel;

namespace SMes.DbMethod.Services
{
    public partial class equipmentoperationlogsService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IequipmentoperationlogsRepository _repository;//访问数据库
       

        [ActivatorUtilitiesConstructor]
        public equipmentoperationlogsService(
            IequipmentoperationlogsRepository dbRepository,
            IHttpContextAccessor httpContextAccessor, pprecords_mainService pprecords_MainService
            
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        /// <summary>
        /// 设备报工
        /// </summary>
        /// <param name="LotNo"></param>
        /// <param name="equipmentCode"></param>
        /// <param name="status">-1异常 0开始 1完成</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> ReportWorking(string LotNo,string equipmentCode,int status)
        {          
            var tmpEquipment = await _repository.DbContext.Set<equipment>().AsNoTracking()
                 .FirstOrDefaultAsync(m => m.SerialNo == equipmentCode);
            if (tmpEquipment == null)
                return new WebResponseContent().ErrorCustom($" report lotNo  {LotNo} prodcut relation：{equipmentCode} No exit,please Check IoT....");
            var step = await _repository.DbContext.Set<pprecords_main>().AsNoTracking()
                 .FirstOrDefaultAsync(m => m.LotNo == LotNo);
            if (step == null)
                return new WebResponseContent().ErrorCustom($" report lotNo  {LotNo} No exit,please start work....");
            //查询当前设备对应的工序已经工步
            var pprecords_Step =await _repository.DbContext.Set<pprecords_step>()
                .AsNoTracking()
                .FirstOrDefaultAsync(m => m.BatchNo == LotNo);
            var updateTime = DateTime.Now;
            if (status > 0){
              var oldEquipmentoperationlogs=await _repository.FindAsIQueryable(m => m.BatchNo == LotNo)
                    .OrderBy(m=>m.StartTime).FirstOrDefaultAsync();
                if (oldEquipmentoperationlogs != null&& oldEquipmentoperationlogs.StartTime!=null)
                {
                    updateTime= (DateTime)oldEquipmentoperationlogs.StartTime;
                }
            }
            //添加设备操作记录
            await  _repository.AddAsync(new equipmentoperationlogs
            {
                OperationID = Guid.NewGuid().ToString(),
                LotID = step.LotID,
                StepID =pprecords_Step==null? null:pprecords_Step.StepID,
                EquipmentID = tmpEquipment.EquipmentID,
                OperationStatus = status < 0 ? "aborted" : status > 0 ? "completed" : "running",
                BatchNo= LotNo,
               // Notes = "LotNo",
                OutputQuantity = 1,
                StartTime = updateTime,
                EndTime = status!=0? DateTime.Now:null
            });
            repository.SaveChanges();
            var res = new WebResponseContent().OK("add success...");
            res.Code = "200";
            return res;
        }
        /// <summary>
        /// 设备开工
        /// </summary>
        /// <param name="LotNo"></param>
        /// <param name="equipmentCode"></param>
        /// <param name="status">-1异常 0开始 1完成</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> StartWorking(string LotNo)
        {
            var step = await _repository.DbContext.Set<pprecords_main_copy>().AsNoTracking()
                 .FirstOrDefaultAsync(m => m.LotNo == LotNo);
            if (step == null)
                return new WebResponseContent().ErrorCustom($" report lotNo  {LotNo} No exit,please start work....");
            //开始作业
            var pprecords_Step = await _repository.DbContext.Set<pprecords_main>().AddAsync(new pprecords_main
            {
                LotID = step.LotID,
                LotNo = step.LotNo,
                ProductCode = step.ProductCode,
                PlanNo = step.PlanNo,
                Status = 1,
                CreateTime = DateTime.Now
            });
            var productionbatches =await _repository.DbContext.Set<productionbatches>()
                .FirstOrDefaultAsync(m => m.BatchID == step.BatchID);
            if (productionbatches == null)
            {
                return new WebResponseContent().ErrorCustom($" report lotNo  {LotNo} prodcut relation：No exit,please Check IoT....");
            }
            var qun= productionbatches.FinishQuantity ;
            var amount = Convert.ToInt32(productionbatches.Quantity)- Convert.ToInt32(productionbatches.StartPartNum??1);
            productionbatches.Status = amount >= qun ? 3:1;
            productionbatches.EndDate = DateTime.Now;
            productionbatches.FinishQuantity = qun + 1;
            _repository.DbContext.Set<productionbatches>().Update(productionbatches);
            //添加设备操作记录
            _repository.DbContext.SaveChanges();
            var res = new WebResponseContent().OK("add success...");
            res.Code = "200";
            return res;
        }
        //if (equip_Group != null)
        //       {
        //           var tempStepId = Guid.NewGuid().ToString();
        //           ////查询工序最新作业记录
        //           var pprecords = await _repository.DbContext.Set<pprecords_process>().AsNoTracking().OrderBy(x => x.CreateTime)
        //              .FirstOrDefaultAsync(m => m.LotID == step.LotID);
        //           ///查询设备设置的工序
        //           var route_Detail = await _repository.DbContext.Set<process_route_detail>().AsNoTracking()
        //               .FirstOrDefaultAsync(m => m.detail_id == equip_Group.work_procedure.Process_id) ??
        //            throw new Exception($"工序作业表{LotNo}{equipmentCode}工序表异常，请将当前设备添加至工艺路线中....");
        //           var Process_id = pprecords == null ? Guid.NewGuid().ToString() : pprecords.ProcessID;
        //           if (pprecords == null || pprecords.ProcessName == route_Detail.routeName)
        //           {
        //               var Nextroute_Detail = await _repository.DbContext.Set<process_route_detail>().AsNoTracking()
        //               .FirstOrDefaultAsync(m => m.parentid == route_Detail.detail_id);

        //               ////添加工序作业记录====后续更新完成---待定
        //               _repository.DbContext.Set<pprecords_process>().Add(new pprecords_process
        //               {
        //                   ProcessID = Process_id,
        //                   ProcessName = route_Detail.routeName,
        //                   ProcessCode = route_Detail.routeName,
        //                   ProcessingStatus = 1,
        //                   SeqNum = route_Detail.sequence,
        //                   LotID = step.LotID,
        //                   IsEndProcess = Nextroute_Detail == null ? 1 : 0,
        //                   // NextProcessID = Nextroute_Detail == null ? null : Nextroute_Detail.detail_id,
        //                   CreateTime = DateTime.Now
        //               });
        //           }
        //           ////添加工步作业记录
        //           _repository.DbContext.Set<pprecords_step>().Add(new pprecords_step
        //           {
        //               StepID = tempStepId,
        //               StepCode = equip_Group.work_procedure.StepNo.ToString(),
        //               StepName = equip_Group.work_procedure.Step_name,
        //               StepSeqNum = equip_Group.work_procedure.StepNo,
        //               ProcessID = Process_id,
        //               BatchNo = step.LotID,
        //               StepStatus = 1,
        //               EquipmentCode = tmpEquipment.SerialNo,
        //               IsEndStep = 0,
        //               CreateTime = DateTime.Now
        //           });
        //           //添加设备操作记录
        //           _repository.Add(new equipmentoperationlogs
        //           {
        //               OperationID = Guid.NewGuid().ToString(),
        //               LotID = step.LotID,
        //               StepID = tempStepId,
        //               EquipmentID = tmpEquipment.EquipmentID,
        //               OperationStatus = status < 0 ? "异常" : status > 0 ? "完成" : "进行中",
        //               Notes = "LotNo",
        //               OutputQuantity = 1,
        //               StartTime = DateTime.Now
        //           });
        //           repository.SaveChanges();
        //       }
        //       else
        //       {
        //           //添加设备操作记录
        //           _repository.Add(new equipmentoperationlogs
        //           {
        //               OperationID = Guid.NewGuid().ToString(),
        //               LotID = step.LotID,
        //               EquipmentID = tmpEquipment.EquipmentID,
        //               OperationStatus = status < 0 ? "异常" : status > 0 ? "完成" : "进行中",
        //               Notes = "LotNo",
        //               OutputQuantity = 1,
        //               StartTime = DateTime.Now
        //               //EndTime = DateTime.Now
        //           });


        //          repository.SaveChanges();
        //

 
    }
}
